package com.chushouya.order.service.api.impl;

import com.alipay.api.response.AlipayOpenMiniOrderQueryResponse;

import com.chushouya.manager.service.common.AlipayClientCommonService;
import com.chushouya.order.constants.AlipayFinishAllDeliveryEnum;
import com.chushouya.order.constants.OrderTypeEnum;
import com.chushouya.order.dao.entity.OrderEntity;
import com.chushouya.order.dao.entity.OrderExtendEntity;
import com.chushouya.order.dao.repository.OrderExtendRepository;
import com.chushouya.order.dao.repository.OrderRepository;
import com.chushouya.order.service.api.AlipayOpenMiniFlowService;
import com.chushouya.order.service.async.OrderAlipayAsyncFactory;
import com.chushouya.order.service.async.OrderAsyncManager;
import com.general.framework.core.exception.Ex;
import com.general.framework.core.lang.Jsons;
import com.general.framework.core.lang.Lists;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

@Service
@Slf4j
public class AlipayOpenMiniFlowServiceImpl implements AlipayOpenMiniFlowService {

    @Resource
    private OrderRepository orderRepository;

    @Resource
    private OrderExtendRepository orderExtendRepository;

    @Resource
    private AlipayClientCommonService alipayClientCommonService;



    /**
     * 获取订单信息
     * @param orderId
     */
    private OrderEntity getOrder(Long orderId) {
        OrderEntity orderEntity = orderRepository.selectByPrimaryKey(orderId);
        if (Objects.isNull(orderEntity)) {
            throw Ex.business("订单不存在");
        }
        return orderEntity;
    }

    /**
     * 订单额外信息
     * @param orderId
     */
    private OrderExtendEntity getOrderExtend(Long orderId) {
        OrderExtendEntity orderExtendEntity = orderExtendRepository.selectByOrderId(orderId);
        if (Objects.isNull(orderExtendEntity)) {
            throw Ex.business("订单扩展信息不存在");
        }
        return orderExtendEntity;
    }

    @Override
    public void alipayFlow(Long orderId) {
        OrderEntity orderEntity = getOrder(orderId);
        OrderExtendEntity orderExtendEntity = getOrderExtend(orderId);
        final String orderNo = orderEntity.getOrderNo();
        final String openId = orderExtendEntity.getOpenId();
        final Integer orderType = orderEntity.getOrderType();

        List<String> orderStatusCircuit = getOrderStatusCircuit(orderType);
        log.info("订单流转流程：{}", orderStatusCircuit);
        String alipayStatus = alipayOpenMiniOrderQuery(orderNo,orderEntity.getPartnerOrderNo(), openId);
                //获取待执行的状态
        List<String> nextStatusList = getNextStatusList(orderStatusCircuit, alipayStatus);
        if(Lists.isEmpty(nextStatusList)){
            throw Ex.business("待流转的状态为空");
        }
        log.info("待执行的状态：{}", nextStatusList);

        //执行状态流转
        for (String status : nextStatusList) {
            handleStatusAction(status, orderEntity);
        }

    }



    /**
     * 获取订单流转流程
     * @param orderType
     */
    private List<String> getOrderStatusCircuit(Integer orderType) {
        if (Objects.equals(orderType, OrderTypeEnum.EXPRESS_RECYCLE.value())) {
            // 快递回收流程：包含部分发货状态
            return Lists.asList("INIT", "PAID", "PARTIAL_DELIVERED", "DELIVERED", "RECEIVED_CONFIRM", "MERCHANT_CONFIRMED");
        } else if (Objects.equals(orderType, OrderTypeEnum.DOOR_RECYCLE.value())) {
            // 上门回收流程：简化流程，无部分发货状态
            return Lists.asList("INIT", "PAID", "DELIVERED", "MERCHANT_CONFIRMED");
        } else {
            throw Ex.business("不支持的订单类型：" + orderType);
        }
    }




    /**
     * 查询支付宝小程序订单状态
     */
    private String alipayOpenMiniOrderQuery(String orderNo,String partnerOrderNo,String openId){
        AlipayOpenMiniOrderQueryResponse response = alipayClientCommonService.alipayOpenMiniOrderQuery(orderNo, openId);
        if (Objects.isNull(response)) {
            throw Ex.business("支付宝小程序订单查询失败");
        }
        if (!response.isSuccess()) {
            throw Ex.business("支付宝小程序订单查询失败");
        }
        if (Objects.isNull(response.getStatus())) {
            throw Ex.business("支付宝小程序订单状态不存在");
        }
        return response.getStatus();
    }

    /**
     * 根据订单状态获取待执行的状态
     */
    private List<String> getNextStatusList(List<String> orderStatusCircuit, String orderStatus) {
//        ["INIT","PART_DELIVERED","DELIVERED","RECEIVED_CONFIRM","MERCHANT_CONFIRMED"]
        if (!orderStatusCircuit.contains(orderStatus)) {
            log.info("当前订单状态不在流转流程中，当前状态：{} 流转状态：{}", orderStatus, orderStatusCircuit);
            throw Ex.business("当前订单状态不在流转流程中");
        }
        int index = orderStatusCircuit.indexOf(orderStatus);
        if (index == orderStatusCircuit.size() - 1) {
            return Lists.emptyList();
        }
        List<String> nextStatusList = orderStatusCircuit.subList(index + 1, orderStatusCircuit.size());
        if (Lists.isEmpty(nextStatusList)) {
            throw Ex.business("订单流转流程不存在");
        }
        return nextStatusList;
    }

    /**
     * 根据状态执行对应的操作
     */
    private void handleStatusAction(String status, OrderEntity orderEntity) {
        final Long orderId = orderEntity.getOrderId();
        switch (status) {
            case "INIT":
                break;
            case "PARTIAL_DELIVERED":
                handleDeliveryGeneratedSend(orderEntity);
                break;
            case "DELIVERED":
                handleDeliverySend(orderEntity);
                break;
            case "RECEIVED_CONFIRM":
                handleDeliveryReceive(orderEntity);
                break;
            case "MERCHANT_CONFIRMED":
                handleQualityCheck(orderEntity);
                break;
            default:
                throw Ex.business("待流转的状态不支持");
        }
    }

    /**
     * 预约快递
     */
    private void handleDeliveryGeneratedSend(OrderEntity orderEntity){
        final Long orderId = orderEntity.getOrderId();
        log.info("订单PARTIAL_DELIVERED成功，订单号：{}", orderId);
        OrderAsyncManager.me().executeDelay1s(OrderAlipayAsyncFactory.alipayOrderDelivery(orderId,AlipayFinishAllDeliveryEnum.GENERATED_LOGISTICS_ORDER.value()));
    }

    /**
     * 订单发货
     */
    private void handleDeliverySend(OrderEntity orderEntity){
        final Long orderId = orderEntity.getOrderId();
        log.info("订单PARTIAL_DELIVERED成功，订单号：{}", orderId);
        OrderAsyncManager.me().executeDelay2s(OrderAlipayAsyncFactory.alipayOrderDelivery(orderId, AlipayFinishAllDeliveryEnum.COURIER_HAS_PICKED_UP.value()));
    }

    /**
     * 订单收货
     */
    private void handleDeliveryReceive(OrderEntity orderEntity){
        final Long orderId = orderEntity.getOrderId();
        log.info("订单RECEIVED_CONFIRM成功，订单号：{}", orderId);
        OrderAsyncManager.me().executeDelay3s(OrderAlipayAsyncFactory.alipayOrderReceive(orderId));

    }

    /**
     * 订单质检
     */
    private void handleQualityCheck(OrderEntity orderEntity){
        final Long orderId = orderEntity.getOrderId();
        log.info("订单MERCHANT_CONFIRMED成功，订单号：{}", orderId);
        OrderAsyncManager.me().executeDelay4s(OrderAlipayAsyncFactory.alipayOrderQuality(orderId));
//        OrderAsyncManager.me().executeDelay5s(OrderAlipayAsyncFactory.alipayOrderQuality(orderId));
    }
}
